<template>
	<div class="q-pa-md">
		<q-table title="明细信息" :rows="rows" :columns="columns" :pagination="paginationOptions" row-key="name">
			<template v-slot:top-right>
				<q-input filled v-model="dateText">
					<template v-slot:append>
						<q-icon name="event" class="cursor-pointer">
							<q-popup-proxy cover transition-show="scale" transition-hide="scale" ref="datePopup">
								<q-date v-model="dateRangeText" range @range-end ="ss" @input="closeDatePopup"
									mask="YYYY-MM-DD">
								</q-date>
							</q-popup-proxy>
						</q-icon>
					</template>
				</q-input>
				<q-btn color="primary" icon-right="archive" label="导出" no-caps @click="exportTable" class="q-ml-sm" />
			</template>
			<template v-slot:header="props">
				<q-tr :props="props">
					<q-th auto-width />
					<q-th v-for="col in props.cols" :key="col.name" :props="props">
						{{ col.label }}
					</q-th>
				</q-tr>
			</template>
			<template v-slot:body="props">
				<q-tr :props="props">
					<q-td auto-width>
						<q-btn round color="primary" icon="mdi-loupe" size="md" @click="dd(props.row)"/>
					</q-td>
					<q-td v-for="col in props.cols" :key="col.name" :props="props">
						{{ col.value }}
					</q-td>
				</q-tr>
			</template>
		</q-table>
	</div>
</template>

<script>
import { exportFile } from 'quasar';
import { v } from 'vxe-table';

// 封装的 CSV 值包装函数
const wrapCsvValue = (val, formatFn, row) => {
	let formatted = typeof formatFn === 'function' ? formatFn(val, row) : val;
	formatted = formatted === undefined || formatted === null ? '' : String(formatted);
	return `"${formatted.split('"').join('""')}"`;
};

export default {
	data() {
		return {
			// 分页选项
			paginationOptions: {
				rowsPerPage: 10,
			},
			// 表格列定义
			columns: [
				{
					name: "业务员",
					label: "业务员",
					field: "业务员",
					align: "center",
					sortable: true,
				},
				{
					name: "部门",
					label: "部门",
					field: "部门",
					align: "center",
					sortable: true,
				},
				{
					name: "销售量",
					label: "销售量",
					field: "销售量",
					align: "center",
					sortable: true,
				},
				{
					name: "自营销售量",
					label: "自营销售量",
					field: "自营销售量",
					align: "center",
					sortable: true,
				},
				{
					name: "终端销售量",
					label: "终端销售量",
					field: "终端销售量",
					align: "center",
					sortable: true,
				},
			],
			// 表格显示的行数据
			rows: [],
			showDialog: false,
			startDate: '',
			endDate: '',
			dateRangeText: '',
			dateText: ''
		};
	},
	async mounted() {
		try {
			this.$q.loading.show();
			// 调用 API 获取数据
			//this.rows = await this.$API.free.wangfang1.get();
		} catch (error) {
			// 处理数据获取失败的情况
			console.error('Failed to fetch data:', error);
			this.$q.notify({
				message: '数据获取失败，请稍后重试',
				color: 'negative',
				icon: 'warning',
			});
		} finally {
			// 隐藏加载提示
			this.$q.loading.hide();
		}
	},
	methods: {
		dd(row) {
			console.log(row);
		},
		async ss(val) {
			console.log(val);
			if(val.from.month<10){
				val.from.month = '0' + val.from.month;
			}
			if(val.from.day<10){
				val.from.day = '0' + val.from.day;
			}
			if(val.to.month<10){
				val.to.month = '0' + val.to.month;
			}
			if(val.to.day<10){
				val.to.day = '0' + val.to.day;
			}
			var start = val.from.year + '-' + val.from.month + '-' + val.from.day;
			var end = val.to.year + '-' + val.to.month + '-' + val.to.day;
			this.dateText = start + ' 至 ' + end;
			this.dateRangeText = {from: start, to: end};
			try {
				this.$q.loading.show();
				// 调用 API 获取数据
				this.rows = await this.$API.free.wangfang2.get(this.dateRangeText);
			} catch (error) {
				// 处理数据获取失败的情况
				console.error('Failed to fetch data:', error);
				this.$q.notify({
					message: '数据获取失败，请稍后重试',
					color: 'negative',
					icon: 'warning',
				});
			} finally {
				// 隐藏加载提示
				this.$q.loading.hide();
			}
			this.$refs.datePopup.hide();
		},
		closeDatePopup() {
			this.$refs.datePopup.hide();
		},
		exportTable() {
			try {
				let filteredRows = this.rows;
				if (this.dateRangeText.length === 2) {
					const startDate = new Date(this.dateRangeText[0]);
					const endDate = new Date(this.dateRangeText[1]);
					// 假设数据中有一个日期字段 'date'，需要根据实际情况修改
					filteredRows = this.rows.filter(row => {
						const rowDate = new Date(row.date);
						return rowDate >= startDate && rowDate <= endDate;
					});
				}

				const headers = this.columns.map((col) => wrapCsvValue(col.label));
				const dataRows = filteredRows.map((row) =>
					this.columns
						.map((col) =>
							wrapCsvValue(
								typeof col.field === 'function' ? col.field(row) : row[col.field || col.name],
								col.format,
								row
							)
						)
						.join(',')
				);
				const content = [headers, ...dataRows].join('\r\n');

				const status = exportFile('table-export.csv', content, 'text/csv');

				if (!status) {
					this.$q.notify({
						message: '浏览器拒绝文件下载，请检查浏览器设置',
						color: 'negative',
						icon: 'warning',
					});
				}
			} catch (error) {
				console.error('Export failed:', error);
				this.$q.notify({
					message: '导出文件时出现错误，请稍后重试',
					color: 'negative',
					icon: 'warning',
				});
			}
		},
	},
};
</script>

<style scoped></style>
